package com.xiaotu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xiaotu.constant.BattleStatus;
import com.xiaotu.constant.RewardPunishEnum;
import com.xiaotu.dto.CoordinateDto;
import com.xiaotu.model.RoomPlayerCoordinateModel;
import com.xiaotu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 张晓
 * @create 2021-10-14 20:52
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BattleHandlerServiceImpl implements BattleHandlerService {

    @Autowired
    private RoomService roomService;

    @Autowired
    private CoordinateService coordinateService;

    @Autowired
    private PlayerService playerService;

    @Autowired
    private PlayerEquipmentService equipmentService;

    public void saveCoordinate(CoordinateDto coordinateDto) {
        RoomPlayerCoordinateModel coordinateModel = new RoomPlayerCoordinateModel();
        BeanUtil.copyProperties(coordinateDto, coordinateModel);
        coordinateService.saveCoordinate(coordinateModel);
    }

    /**
     * 关闭房间
     *
     * @param roomId
     * @param playerList
     */
    public void closeRoom(Integer roomId, List<Session> playerList) {
        roomService.closeRoom(roomId);
        List<Integer> playerIds = playerList.stream().filter(p -> ObjectUtil.isNotNull(p)).map(p -> (Integer) p.getUserProperties().get("playerId")).collect(Collectors.toList());
        playerService.batchUpdateBattleStatus(playerIds, BattleStatus.BATTLEING.getVal());
        equipmentService.deductionGoldCoins(playerIds, RewardPunishEnum.ADMISSION_FEE.getVal());
    }

    /**
     * 激活房间
     *
     * @param roomId
     */
    public void activeRoom(Integer roomId) {
        roomService.activeRoom(roomId);
    }

    /**
     * 销毁房间
     *
     * @param roomId
     */
    public void destoryRoom(Integer roomId) {
        roomService.closeRoom(roomId);
    }

    /**
     * 设置玩家游戏状态
     *
     * @param player
     */
    public void setPlayerBattleStatus(Session player) {
        Integer playerId = (Integer) player.getUserProperties().get("playerId");
        playerService.setPlayerBattleStatus(playerId, BattleStatus.PREPARING.getVal());
    }

    /**
     * 是否有入场资格
     *
     * @param playerId
     * @return
     */
    public boolean isAdmissionAllowed(Integer playerId) {
        return equipmentService.isAdmissionAllowed(playerId);
    }

    /**
     * 清除房间历史走棋记录
     *
     * @param roomId
     */
    public void clearHistoryCoordinate(Integer roomId) {
        coordinateService.clearHistoryCoordinate(roomId);
    }
}
